import { get, post } from '@common/ajax';
import { SHOP_URL } from '@common/url';
import logger from '@common/logger';

import {
    GET_CLASSIFY_LIST,
    SET_CLASSIFY_SHELF_PARAM,
    GET_CLASSIFY_SHELF_LIST,
} from '@store/mutationType';
import { Tip } from '@common/tip';

const classify = {
    state: {
        categoryList: [], // 分类数据
        shelfList: [],
        // 分页相关参数
        searchValue: '',
        categoryId: '',
        pageNumber: 1,
        pageSize: 10,
    },
    mutations: {
        GET_CLASSIFY_LIST: (state, categoryList) => {
            Object.assign(state, { categoryList });
        },
        SET_CLASSIFY_SHELF_PARAM: (state, { pageNumber, categoryId }) => {
            Object.assign(state, { pageNumber, categoryId });
        },
        GET_CLASSIFY_SHELF_LIST: (state, shelfList) => {
            Object.assign(state, { shelfList });
        },
    },
    actions: {
        // 获取类别信息
        getClassifyList: async ({ commit, dispatch }) => {
            const res = await get(SHOP_URL.group, { id: 0 });
            commit(GET_CLASSIFY_LIST, [{
                id: 0,
                name: '全部',
            }, ...res.groups]);
            dispatch('getClassifyShelf', 0);
        },
        // 获取类别数据
        getClassifyShelf: async ({ commit, state }, categoryId) => {
            const { pageSize, searchValue } = state;
            const param = {
                id: 0,
                group_id: categoryId,
                query: searchValue,
                page_no: 1,
                page_size: pageSize,
            };
            const res = await get(SHOP_URL.shelf, param);
            logger.success('Classify => 类别数据', res.prods);
            commit(SET_CLASSIFY_SHELF_PARAM, { pageNumber: 1, categoryId });
            commit(GET_CLASSIFY_SHELF_LIST, res.prods);
        },
        // 获取类别数据-下一页
        getClassifyShelfNext: async ({ commit, state }) => {
            const { categoryId, pageNumber, pageSize, shelfList, searchValue } = state;
            const pageNo = pageNumber + 1;
            const param = {
                id: 0,
                group_id: categoryId,
                query: searchValue,
                page_no: pageNo,
                page_size: pageSize,
            };
            const res = await get(SHOP_URL.shelf, param);
            const result = [...shelfList, ...res.prods];
            commit(SET_CLASSIFY_SHELF_PARAM, { pageNumber: pageNo, categoryId });
            commit(GET_CLASSIFY_SHELF_LIST, result);
            res.prods.length === 0 && Tip('已加载全部数据');
        },
    },
};

export default classify;
